package com.yunbao.core.shiro;

import com.yunbao.core.shiro.jwt.JwtToken;
import com.yunbao.core.shiro.jwt.JwtUtil;
import com.yunbao.project.entity.Merchant;
import com.yunbao.project.service.IMerchantService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * <p>
 * 用户Realm
 * </p>
 *
 * @author 安能
 * @date 2019年1月18日
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {


    @Resource
    IMerchantService merchantService;


    /**
     * 必须重写此方法，不然Shiro会报错
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    /**
     * <p>
     * 只有当需要检测用户权限的时候才会调用此方法，例如checkRole,checkPermission之类的
     * </P>
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {


//        给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();


        return info;
    }

    /**
     * <p>
     * 认证（登录）
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     * </P>
     *
     * @param auth
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {

        try {
            String token = (String) auth.getCredentials();
            // 解密获得username，用于和数据库进行对比
            Merchant merchant = JwtUtil.getMerchant(token);
//            log.info("{}", merchant);
            if (merchant == null) {

                throw new AuthenticationException("token无效!");

            }
            Merchant merchantById = merchantService.getById(merchant.getId());
            if (merchantById == null) {
                throw new AuthenticationException("用户不存在!");
            }

            if (!JwtUtil.verify(token, merchantById)) {
                throw new AuthenticationException("用户名或密码错误");
            }
//            log.info("AuthenticationInfo通过{}", merchant);
            return new SimpleAuthenticationInfo(token, token, "myRealm");
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        return null;
    }
}
